// 云函数模板
// 部署：在 cloud-functions/login 文件夹右击选择 “上传并部署”

const cloud = require('wx-server-sdk');
const request = require('request');

// 初始化 cloud
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})

/**
 * 这个示例将经自动鉴权过的小程序用户 openid 返回给小程序端
 * 
 * event 参数包含小程序端调用传入的 data
 * 
 */
exports.main = (event, context) => {

  //console.log(event);
  //console.log(context);
  const wxContext = cloud.getWXContext();
  const db = cloud.database();

  if (typeof (event.lon) !== 'Number') {
    event.lon = 90;
  };
  if (typeof (event.lat) !== 'Number') {
    event.lat = 0;
  };

  /*************后台存储  **************/
  const url = "http://47.114.59.59:8088/api/login";

  var requestData = {
    openId: wxContext.OPENID,
    env: wxContext.ENV,
    unionId: wxContext.UNIONID,
    source: wxContext.SOURCE
  };
  request({
    url: url,
    method: "POST",
    json: true,
    headers: {
      "content-type": "application/json",
    },
    body: JSON.stringify(requestData)
  }, function (error, response, body) {

    if (!error && response.statusCode == 200 && !body.error) {
      console.log(body) // 请求成功的处理逻辑

      /*********云数据库存储  **************/
      db.collection('user').where({
        _openId: wxContext.OPENID
      }).get().then(res => {

        /****新增 */
        if (res.data.length == 0) {

          db.collection('user').add({
            data: {
              _openId: wxContext.OPENID,
              env: wxContext.ENV,
              unionId: wxContext.UNIONID,
              source: wxContext.SOURCE,
              location: new db.Geo.Point(event.lon, event.lat),
              type: 2,
              createTime: new Date(),
              updateTime: new Date(),
              status: true
            }
          }).then(res => {
            console.log('create user:', res);
          });

        } else {
          /****更新 */
          db.collection('user').where({
            _openId: wxContext.OPENID
          }).update({
            data: {
              updateTime: new Date(),
              location: new db.Geo.Point(event.lon, event.lat)
            }
          }).then(res => {
            console.log('update user:', res);
          });
        };

      });

      return {
        error: null,
        code: body.loginTime
      };

    } else {
      console.log('error', error)
      return {
        error: error
      };
    };

  });

}
